package com.sayi.dzapi.controller;


import org.springframework.http.HttpStatus;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.server.ResponseStatusException;

import org.springframework.dao.EmptyResultDataAccessException;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/threads")
public class ThreadController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/test")
    public String test(){
        return "done.";
    }

    @GetMapping({"", "/", "/{tid}"})
    public ResponseEntity<?> getThreadsOrThreadByTid(
            @PathVariable(value = "tid", required = false) Integer tid,
            @RequestParam(value = "page", required = false, defaultValue = "1") int page) {

        int pageSize = 10; // 每页显示的记录数
        int offset = (page - 1) * pageSize; // 计算偏移量

        if (tid != null) {
            String sql = "SELECT * FROM pre_forum_thread WHERE tid = :tid";
            MapSqlParameterSource parameters = new MapSqlParameterSource();
            parameters.addValue("tid", tid);

            try {
                Map<String, Object> thread = new NamedParameterJdbcTemplate(jdbcTemplate).queryForMap(sql, parameters);
                return ResponseEntity.ok(thread);
            } catch (EmptyResultDataAccessException e) {
                return ResponseEntity.ok(Collections.emptyMap());
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
            }
        } else {
            String sql = "SELECT * FROM pre_forum_thread ORDER BY tid DESC LIMIT :pageSize OFFSET :offset";
            MapSqlParameterSource parameters = new MapSqlParameterSource();
            parameters.addValue("pageSize", pageSize);
            parameters.addValue("offset", offset);

            List<Map<String, Object>> threads = new NamedParameterJdbcTemplate(jdbcTemplate).queryForList(sql, parameters);
            return ResponseEntity.ok(threads);
        }
    }
}
